package com.ruoyi.web.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/sns")
public class SnsLoginController {

    @Resource
    private RestTemplate restTemplate;

    /**
     * 获取code
     *
     * @param platformName
     * @param response
     * @throws Exception
     */
    @GetMapping("authorize/{platformName}")
    public void authorize(@PathVariable String platformName, HttpServletResponse response) throws Exception {
        //传入应用id、回调地址
        response.sendRedirect("https://gitee.com/oauth/authorize?client_id=4c4023a5dd80380da72d7ac06c108da231d67a38d2ab051f56f76a3818c2b553" +
                "&redirect_uri=http://localhost/login&response_type=code");
    }

    /**
     * 获取授权码成功后，第三方应用自动回调前端页面（在第三方应用中配置的回调地址）
     * 前端页面根据授权码调用/{platformName}/snsLogin控制器
     * /{platformName}/snsLogin控制器根据授权码获取accessToken
     * 根据accessToken获取用户信息
     * 根据用户信息创建token返回给前端
     * 前端在异步回调方法中获取token后设置登录成功并路由
     *
     * @throws Exception
     */
    @GetMapping("{platformName}/snsLogin")
    public AjaxResult snsLogin(String code) {
        //621e1a320ac444084fea87b1f78b7b496268d6def96712c7a06bb6d4c8b53176
        System.out.println("code = " + code);
        String url = "https://gitee.com/oauth/token?grant_type=authorization_code" +
                "&code=" + code +
                "&client_id=4c4023a5dd80380da72d7ac06c108da231d67a38d2ab051f56f76a3818c2b553" +
                "&redirect_url=http://localhost/login" +
                "&client_secret=a7bf5003fc65b904eabbf401b9098b97edb169e577674285e6f89fd653bf8a4d";
        Map map = restTemplate.postForObject(url, null, Map.class);
        System.out.println("map" + map);
        return AjaxResult.success();
    }
}
